{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "import numpy as np"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## algorithm"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "def reservoir_sampling(size):\n",
    "    i, sample = 0, []\n",
    "\n",
    "    while True:\n",
    "        item = yield i, sample\n",
    "        \n",
    "        i += 1\n",
    "        k = np.random.randint(0, i)\n",
    "\n",
    "        if len(sample) < size:\n",
    "            sample.append(item)\n",
    "        elif k < size:\n",
    "            sample[k] = item"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## run"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "100 [15, 49, 54, 63, 60]\n",
      "200 [180, 49, 54, 63, 197]\n",
      "300 [218, 49, 54, 63, 197]\n",
      "400 [218, 49, 54, 63, 197]\n",
      "500 [218, 49, 54, 63, 197]\n",
      "600 [519, 49, 54, 63, 197]\n",
      "700 [691, 49, 54, 63, 197]\n",
      "800 [691, 49, 54, 63, 197]\n",
      "900 [691, 49, 54, 63, 197]\n",
      "1000 [691, 49, 54, 63, 197]\n"
     ]
    }
   ],
   "source": [
    "reservoir = reservoir_sampling(5)\n",
    "next(reservoir)\n",
    "\n",
    "for i in range(1000):\n",
    "    k, sample = reservoir.send(i)\n",
    "    if k % 100 == 0:\n",
    "        print(k, sample)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.0"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
